package top.cardone.context.action;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.io.Resource;
import top.cardone.core.util.action.Action0;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author yao hai tao
 * @date 2017/10/12
 */
@Log4j2
public class RunExesAction implements Action0 {
    @Setter
    private Resource[] execs;

    @Override
    public void action() {
        if (ArrayUtils.isEmpty(execs)) {
            return;
        }

        for (Resource exec : execs) {
            if (!exec.exists()) {
                continue;
            }

            try {
                if (!("/".equals(File.separator) && "sh".equals(FilenameUtils.getExtension(exec.getFile().getName())))) {
                    continue;
                }
            } catch (IOException e) {
                log.error(e);
            }

            try {
                String s = StringUtils.join(new String[]{exec.getFile().getAbsolutePath(),
                        DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"),
                        String.valueOf(LocalDate.now().getYear()),
                        String.valueOf(LocalDate.now().minusYears(1).getYear()),
                        LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM")),
                        LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM")),
                        LocalDate.now().minusMonths(2).format(DateTimeFormatter.ofPattern("yyyyMM"))
                }, " ");

                Process ps = Runtime.getRuntime().exec(s);

                ps.waitFor();

                try (Reader reader = new InputStreamReader(ps.getInputStream())) {
                    try (BufferedReader bufferedReader = new BufferedReader(reader)) {
                        StringBuffer sb = new StringBuffer();

                        String line;

                        while ((line = bufferedReader.readLine()) != null) {
                            sb.append(line).append("\n");
                        }

                        if (log.isDebugEnabled()) {
                            log.debug(sb.toString());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
